package com.econ.powercloud.ems.timing.report.prometheus.callback;

import com.econ.powercloud.console.facade.utils.CacheKeyUtils;
import com.econ.powercloud.ems.common.util.JacksonExtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public abstract class AbstractPrometheusMultiDataCallback {

    final protected Integer MAX_INSTANCE_COUNT = 10;

    final private String INSTANCE_KEY_TEMPLATE = "data.result[%s].metric.instance";

    final private String VALUE_KEY_TEMPLATE = "data.result[%s].value[1]";

    abstract String getCategory();

    abstract String getItem();

    @Autowired
    protected StringRedisTemplate stringRedisTemplate;

    protected String getInstanceKey(Integer number){
        return String.format(INSTANCE_KEY_TEMPLATE, number);
    }

    protected String getValueKey(Integer number){
        return String.format(VALUE_KEY_TEMPLATE, number);
    }

    public void dealWithPrometheusCallbackData(String content) {
        Map<String, String> prometheusResult = JacksonExtUtil.flatJsonToMap(content);
        for(int i = 0; i < MAX_INSTANCE_COUNT ; i++){
            String instanceKey = getInstanceKey(i);
            if(!prometheusResult.containsKey(instanceKey)){
                break;
            }
            String instance = (String)prometheusResult.get(instanceKey).replaceAll(":", "-");
            String value = prometheusResult.get(getValueKey(i));
            String redisKey = CacheKeyUtils.getMonitorDataKey(instance, getCategory());
            HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
            hashOperations.put(redisKey, getItem(), value);
        }
    }
}
